<script setup lang="ts">
import { ref, onBeforeMount, onMounted } from 'vue'

import { formatDate } from '@/utils/util'
import request from '@/utils/request'

import Calendar from '@/components/calendar.vue'

type SelectedType = { value: string; status?: number; before?: boolean }

type CalendarData = Record<string, { text: string; status: number }>

let currentYM: string[] // 当前日期（年月）
let currentDate: string // 当前日期

const selected = ref<SelectedType>()
const calendarData = ref<CalendarData>()

onBeforeMount(() => {
  currentDate = formatDate(new Date(), 'yyyy-MM-dd')
  currentYM = formatDate(new Date(), 'yyyy-MM-dd').split('-').slice(0, 2)
  selected.value = { value: currentDate }
})

onMounted(() => init())

/**
 * 初始化
 */
const init = () => {
  getData()
}

/**
 * 获取数据
 */
const getData = async () => {
  const [year, month] = currentYM
  calendarData.value = await request<CalendarData>('/mock/calendar', 'POST', {
    year,
    month,
  })
}

/**
 * 选择
 */
const handleSelect = (value: SelectedType) => {
  selected.value = value
}

/**
 * 确认
 */
const handleConfirm = (value: string[]) => {
  ~(currentYM = value) && getData()
}
</script>

<template>
  <div class="page">
    <Calendar
      :data="calendarData"
      :default="selected.value"
      @select="(event) => handleSelect(event)"
      @confirm="(event) => handleConfirm(event)"
    ></Calendar>
  </div>
</template>

<style scoped lang="scss">
.page {
  height: 100%;
  background-color: #f4f5fb;
}
</style>
